package cn.edu.lingnan.util;

import java.sql.*;
import java.util.HashMap;

//功能：返回一个数据库连接；关闭数据库连接
public class DBUtil {
    private static DBUtil dbUtil;
    private static String driver=null;
    private static String url=null;
    private static String user=null;
    private static String password=null;
    private static String xmlFileName="database.conf.xml";
    private static String xsdFileName="database.conf.xsd";

    static{
        String basePath=Thread.currentThread().getContextClassLoader().getResource("").getPath();
//        System.out.println(basePath);
        xmlFileName=basePath+xmlFileName;
        xsdFileName=basePath+xsdFileName;
        if (XmlValidater.validator(xmlFileName, xsdFileName)) {
            HashMap<String,String>hm=new HashMap<>();
            hm = XmlParser.parser(xmlFileName);
            driver=hm.get("driver");
            url= hm.get("url");
            user= hm.get("user");
            password= hm.get("password");
        }
    }
    private DBUtil() {//私有构造方法
        try {
//            System.out.println(driver);
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public static DBUtil getInstance(){
        if(dbUtil==null){
            dbUtil=new DBUtil();
        }
        return dbUtil;
    }
    public Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }
    public void close(ResultSet rs, Statement st,Connection conn){
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void close(Statement st,Connection conn){
        try {
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
